package com.shelpe.services.simbasync.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shelpe.services.simbasync.dto.AdgroupsDto;
import com.shelpe.services.simbasync.dto.RptAdgroupDto;
import com.shelpe.services.simbasync.exception.ApiException;
import com.shelpe.services.simbasync.exception.RequestParamException;
import com.shelpe.services.simbasync.model.Adgroups;
import com.shelpe.services.simbasync.model.RptAdgroup;
import com.shelpe.services.simbasync.service.AdgroupsService;
import com.shelpe.services.simbasync.service.AuthService;
import com.shelpe.services.simbasync.service.SyncRecordService;
import com.shelpe.services.simbasync.service.UserService;
import com.shelpe.services.simbasync.service.simbaproxy.AdgroupsProxy;
import com.shelpe.services.simbasync.util.Util;

@RestController
@RequestMapping(value="/simbasync")
public class AdgroupsController {
	
	private static final Logger logger = LoggerFactory.getLogger(AdgroupsController.class);
	 
	private static final Map<String, Date> requestPool = new HashMap<String, Date>();
	
	@Autowired
	private AdgroupsProxy proxy;
	
	@Autowired
	private AdgroupsService service;
	
	@Autowired
	private UserService user;
	
	@Autowired
	private AuthService auth;
	
	@Autowired
	private SyncRecordService syncService;
	
	private final ExecutorService executor = Executors.newFixedThreadPool(4);
	
	@RequestMapping("/tenants/{user}/campaigns/{campaign_id}/@adgroup")
	@ResponseBody
	public AdgroupsDto syncAdgroupsByUser(@PathVariable("user") String user, @PathVariable("campaign_id")Long campaignId){
		
		boolean isNumber = user.matches("-?[0-9]+.*[0-9]*");
		
		return isNumber ? syncAdgroups(null, Long.valueOf(user), campaignId) : syncAdgroups(user, null, campaignId);
	}
	
	@RequestMapping("/tenants/{user}/campaigns/{campaign_id}/@adgroupasyn")
	@ResponseBody
	public DeferredResult<AdgroupsDto> syncAdgroupsByUserAsyn(@PathVariable("user") final String user, @PathVariable("campaign_id") final Long campaignId){
		
		final DeferredResult<AdgroupsDto> result = new DeferredResult<AdgroupsDto>();
		final boolean isNumber = user.matches("-?[0-9]+.*[0-9]*");
		CompletionService<AdgroupsDto> comletionService = new ExecutorCompletionService<AdgroupsDto>(executor); 
		
		comletionService.submit(new Callable<AdgroupsDto>(){
                                                                                                                                                                                                    
			@Override
			public AdgroupsDto call() throws Exception {
				// TODO Auto-generated method stub
				AdgroupsDto dto = null;
				if(isNumber){
					dto = syncAdgroups(null, Long.valueOf(user), campaignId);
				}else{
					dto = syncAdgroups(user, null, campaignId);
				}
				
				result.setResult(dto);
				
				return dto;
			}});
		
		return result;
	}
	
	@RequestMapping("/tenants/{user}/campaigns/{campaign_id}/adgroups/{adgroup_id}/@adgroup")
	@ResponseBody
	public AdgroupsDto syncAdgroupsByUserAd(@PathVariable("user") String user, @PathVariable("campaign_id")Long campaignId, @PathVariable("adgroup_id")Long adgroupId){
		
		boolean isNumber = user.matches("-?[0-9]+.*[0-9]*");
		
		return isNumber ? syncAdgroups(null, Long.valueOf(user), campaignId, adgroupId) : syncAdgroups(user, null, campaignId, adgroupId);
	}
	
	@RequestMapping("/tenants/{user}/campaigns/{campaign_id}/@rptadgroup")
	@ResponseBody
	public RptAdgroupDto syncRptAdgroupsByUser(@PathVariable("user") String user, @PathVariable("campaign_id") Long campaignId,
			@RequestParam(value = "start_date", required = false) String startDate, @RequestParam(value = "end_date", required = false) String endDate,
			@RequestParam(value = "record", required = false) String record){

		boolean isNumber = user.matches("-?[0-9]+.*[0-9]*");
		
		return isNumber ? syncRptAdgroups(null, Long.valueOf(user), campaignId, null, startDate, endDate, record) : syncRptAdgroups(user, null, campaignId, null, startDate, endDate, record);
	}
	
	@RequestMapping("/tenants/{user}/campaigns/{campaign_id}/@rptadgroupasyn")
	@ResponseBody
	public DeferredResult<RptAdgroupDto> syncRptAdgroupsByUserAsyn(@PathVariable("user") final String user, @PathVariable("campaign_id") final Long campaignId,
			@RequestParam(value = "start_date", required = false) final String startDate, @RequestParam(value = "end_date", required = false) final String endDate,
			@RequestParam(value = "record", required = false)final String record){
		
		final DeferredResult<RptAdgroupDto> result = new DeferredResult<RptAdgroupDto>();
		final boolean isNumber = user.matches("-?[0-9]+.*[0-9]*");
		CompletionService<RptAdgroupDto> comletionService = new ExecutorCompletionService<RptAdgroupDto>(executor); 
		
		comletionService.submit(new Callable<RptAdgroupDto>(){
                                                                                                                                                                                                    
			@Override
			public RptAdgroupDto call() throws Exception {
				// TODO Auto-generated method stub
				RptAdgroupDto dto = null;
				if(isNumber){
					dto = syncRptAdgroups(null, Long.valueOf(user), campaignId, null, startDate, endDate, record);
				}else{
					dto = syncRptAdgroups(user, null, campaignId, null, startDate, endDate, record);
				}
				
				result.setResult(dto);
				
				return dto;
			}});
		
		return result;
	}
	
	@RequestMapping("/tenants/{user}/campaigns/{campaign_id}/adgroups/{adgroupIds}/@rptadgroup")
	@ResponseBody
	public RptAdgroupDto syncRptAdgroupsByUserAd(@PathVariable("user") String user, @PathVariable("campaign_id") Long campaignId, @PathVariable("adgroupIds") String adgroupIds,
			@RequestParam(value = "start_date", required = false) String startDate, @RequestParam(value = "end_date", required = false) String endDate,
			@RequestParam(value = "record", required = false) String record){//默认不记日志

		boolean isNumber = user.matches("-?[0-9]+.*[0-9]*");
		
		return isNumber ? syncRptAdgroups(null, Long.valueOf(user), campaignId, adgroupIds, startDate, endDate, record) : syncRptAdgroups(user, null, campaignId, adgroupIds, startDate, endDate, record);
	}
	//-----------------------------------------
	
	private AdgroupsDto syncAdgroups(String nick, Long userId, Long campaignId){
		
		if(userId == null){
			userId = user.getUserIdByNick(nick);
		}
		
		if(nick == null){
			nick = user.getNickByUserId(userId);
		}
	       
		if(nick == null || userId == null){
			logger.warn("nick or userId is null, do nothing");
			throw new RequestParamException();
		}
		logger.info(">>>syncAdgroups nick {}, userId {}, campaignId {}", nick, userId, campaignId);
		AdgroupsDto dto = new AdgroupsDto();
		dto.setNick(nick);
		dto.setUserId(userId);
		dto.setProcess("syncAdgroups");
        int pageSize = 100;
		int pageNo = 1;
		int totalItem = 0;
		int pages = 0;
		Date beginProcessTime = new Date();
		
		String requestParam = Util.createKey(null, userId.toString(), campaignId.toString(), null, null);
		if(requestPool.containsKey(requestParam)){
			
			Date lastProcessDate = requestPool.get(requestParam);
			if(beginProcessTime.getTime() - lastProcessDate.getTime() > Util.MilliSecondsOfMin * 5){
				requestPool.remove(requestParam);
				logger.info(">>>syncAdgroups nick {}, userId {}, campaignId {}, process out time, restart new sync task", nick, userId, campaignId);
			}else{
				dto.setMessage("On processing");
				logger.info(">>>syncAdgroups nick {}, userId {}, campaignId {}, request too freq", nick, userId, campaignId);
				return dto;
			}
		}

		requestPool.put(requestParam, beginProcessTime);		
		
		String response = null;
		try{
			response = proxy.getAdgroupsByCampaignId(nick, campaignId, pageSize, pageNo);
		}catch(Exception e){
			logger.warn("Maybe something is wrong or can not find token, userId {}", userId);
		}
		
		if(response != null && response.contains("simba_adgroupsbycampaignid_get_response")){
			JSONObject object = JSON.parseObject(response);
			JSONObject objRes = object==null? null : object.getJSONObject("simba_adgroupsbycampaignid_get_response");
			JSONObject objItems = objRes==null? null : objRes.getJSONObject("adgroups");
			
			totalItem = objItems==null ? 0 : objItems.getIntValue("total_item");
			pages = totalItem/pageSize;
			if(totalItem%pageSize > 0){
				pages++;
			}
		}else{
			logger.warn("can not get any info from proxy, maybe something is wrong, nick is {}, campaignId {}， response {}", nick, campaignId, response);
			if(response != null && response.contains("isv.invalid-permission")){//没有权限
				dto.setMessage("invalid-permission");
				requestPool.remove(requestParam);
				return dto;
			}else if(response != null && response.contains("invalid-sessionkey")){
				dto.setMessage("invalid-sessionkey");
				requestPool.remove(requestParam);
				return dto;
			}else if(response == null){
				dto.setMessage("get no information");
				requestPool.remove(requestParam);
				return dto;
			}else{
				requestPool.remove(requestParam);
				throw new ApiException();
			}
		}
		
		List<Adgroups> listTotal = new ArrayList<Adgroups>();
		try{
			
			List<Adgroups> subList = service.parseJsonToAdgroups(response);
			if(subList != null && subList.size() > 0){
				listTotal.addAll(subList);
			}
			
			for(int i = 2; i <= pages; i++){
				response = proxy.getAdgroupsByCampaignId(nick, campaignId, pageSize, i);
				subList = service.parseJsonToAdgroups(response);
				if(subList != null && subList.size() > 0){
					listTotal.addAll(subList);
				}
			}
			
			service.updateAdgroupsData(userId, listTotal);
			
		}catch(Exception e){
			requestPool.remove(requestParam);
			throw e;
		}
		
		List<Adgroups> oldListTemp = service.getAdgroupsByCampaignId(campaignId);
		
		List<Adgroups> oldList = new ArrayList<Adgroups>();
		
		if(oldListTemp != null){
			oldList.addAll(oldListTemp);
		}

		Map<String, List<Adgroups> > splitAdgroups = service.splitAdgroups(listTotal, oldList);
		dto.setAddNum(service.insertAdgroupsBatch(splitAdgroups.get("add")));
		dto.setUpdateNum(service.updateAdgroupsList(splitAdgroups.get("update")));
		dto.setDeleteNum(service.deleteAdgroupsList(splitAdgroups.get("delete")));
		
		Date endProcessTime = new Date();
		long durTime = endProcessTime.getTime() - beginProcessTime.getTime();
		dto.setDurTime(durTime);
		
		requestPool.remove(requestParam);
		
		return dto;
	}

	private AdgroupsDto syncAdgroups(String nick, Long userId, Long campaignId, Long adgroupId){
		
		if(userId == null){
			userId = user.getUserIdByNick(nick);
		}
		
		if(nick == null){
			nick = user.getNickByUserId(userId);
		}
	       
		if(nick == null || userId == null){
			logger.warn("nick or userId is null, do nothing");
			throw new RequestParamException();
		}
		logger.info(">>>syncAdgroups nick {}, userId {}, campaignId {}", nick, userId, campaignId);
		AdgroupsDto dto = new AdgroupsDto();
		dto.setNick(nick);
		dto.setUserId(userId);
		dto.setProcess("syncAdgroups");
        int pageSize = 100;
		int pageNo = 1;
		int totalItem = 0;
		int pages = 0;
		Date beginProcessTime = new Date();
		String requestParam = Util.createKey(null, userId.toString(), campaignId.toString(), adgroupId.toString(), null);
		if(requestPool.containsKey(requestParam)){
			
			Date lastProcessDate = requestPool.get(requestParam);
			if(beginProcessTime.getTime() - lastProcessDate.getTime() > Util.MilliSecondsOfMin){
				requestPool.remove(requestParam);
				logger.info(">>>syncAdgroups nick {}, userId {}, campaignId {}, adgroupId {}, process out time, restart new sync task", nick, userId, campaignId, adgroupId);
			}else{
				dto.setMessage("On processing");
				logger.info(">>>syncAdgroups nick {}, userId {}, campaignId {}, adgroupId {}, request too freq", nick, userId, campaignId, adgroupId);
				return dto;
			}
		}

		requestPool.put(requestParam, beginProcessTime);		
		
		String response = null;
		try{
			response = proxy.getAdgroupsByCampaignId(nick, campaignId, pageSize, pageNo);
		}catch(Exception e){
			logger.warn("Maybe something is wrong or can not find token, userId {}", userId);
		}
		
		if(response != null && response.contains("simba_adgroupsbycampaignid_get_response")){
			JSONObject object = JSON.parseObject(response);
			JSONObject objRes = object==null? null : object.getJSONObject("simba_adgroupsbycampaignid_get_response");
			JSONObject objItems = objRes==null? null : objRes.getJSONObject("adgroups");
			
			totalItem = objItems==null ? 0 : objItems.getIntValue("total_item");
			pages = totalItem/pageSize;
			if(totalItem%pageSize > 0){
				pages++;
			}
		}else{
			logger.warn("can not get any info from proxy, maybe something is wrong, nick is {}, campaignId {}， response {}", nick, campaignId, response);
			if(response != null && response.contains("isv.invalid-permission")){//没有权限
				dto.setMessage("invalid-permission");
				requestPool.remove(requestParam);
				return dto;
			}else if(response != null && response.contains("invalid-sessionkey")){
				dto.setMessage("invalid-sessionkey");
				requestPool.remove(requestParam);
				return dto;
			}else if(response == null){
				dto.setMessage("get no information");
				requestPool.remove(requestParam);
				return dto;
			}else{
				requestPool.remove(requestParam);
				throw new ApiException();
			}
		}
		
		List<Adgroups> listTotal = new ArrayList<Adgroups>();
		
		try{
			
			List<Adgroups> subList = service.parseJsonToAdgroups(response);
			if(subList != null && subList.size() > 0){
				listTotal.addAll(subList);
			}
			
			for(int i = 2; i <= pages; i++){
				response = proxy.getAdgroupsByCampaignId(nick, campaignId, pageSize, i);
				subList = service.parseJsonToAdgroups(response);
				if(subList != null && subList.size() > 0){
					listTotal.addAll(subList);
				}
			}
			
			service.updateAdgroupsData(userId, listTotal);
			
		}catch(Exception e){
			requestPool.remove(requestParam);
			throw e;
		}
		
		List<Adgroups> newList = new ArrayList<Adgroups>();
		for(Adgroups ad : listTotal){
			if(ad.getAdgroupId().equals(adgroupId)){
				newList.add(ad);
				break;
			}
		}
		
		Adgroups oldAdgroups = service.getAdgroupsById(adgroupId);
		
		if(oldAdgroups == null){
			dto.setAddNum(service.insertAdgroupsBatch(newList));
		}else if(newList.size() == 0){
			dto.setDeleteNum(service.deleteAdgroups(oldAdgroups));
		}else{
			dto.setUpdateNum(service.updateAdgroupsList(newList));
		}
        
		Date endProcessTime = new Date();
		long durTime = endProcessTime.getTime() - beginProcessTime.getTime();
		dto.setDurTime(durTime);
		
		requestPool.remove(requestParam);
		
		return dto;
	}

	private RptAdgroupDto syncRptAdgroups(String nick, Long userId, Long campaignId, String ads, String startDate, String endDate, String record){
		
		if(userId == null){
			userId = user.getUserIdByNick(nick);
		}
		
		if(nick == null){
			nick = user.getNickByUserId(userId);
		}
		
		if(nick == null || userId == null){
			logger.warn("nick or userId is null, do nothing");
			throw new RequestParamException();
		}
		
		logger.info(">>>syncRptAdgroups nick {}, userId {}, campaignId {}", nick, userId, campaignId);
		RptAdgroupDto dto = new RptAdgroupDto();
		dto.setNick(nick);
		dto.setUserId(userId);
		dto.setProcess("syncRptAdgroups");
		Date beginProcessTime = new Date();
		
		String requestParam = Util.createKey("rpt", userId.toString(), campaignId.toString(), ads, endDate);
		if(requestPool.containsKey(requestParam)){
			
			Date lastProcessDate = requestPool.get(requestParam);
			if(beginProcessTime.getTime() - lastProcessDate.getTime() > Util.MilliSecondsOfMin * 5){
				requestPool.remove(requestParam);
				logger.info(">>>syncRptAdgroups nick {}, userId {}, campaignId {}, adgroupId {}, process out time, restart new sync task", nick, userId, campaignId, ads);
			}else{
				dto.setMessage("On processing");
				logger.info(">>>syncRptAdgroups nick {}, userId {}, campaignId {}, adgroupId {}, request too freq", nick, userId, campaignId, ads);
				return dto;
			}
		}
		
		requestPool.put(requestParam, beginProcessTime);
		
		List<Long> adgroupIds = new ArrayList<Long>();
		if(ads != null && (!ads.equals("")) && (!ads.equals("null"))){
			String[] adStr = ads.split(",");
			
			if(adStr != null){
				for(int i = 0; i < adStr.length; i++){
					adgroupIds.add(Long.valueOf(adStr[i]));
				}
			}
		}
		
		if(adgroupIds.size() == 0){
			
			List<Adgroups> adgroups = service.getAdgroupsByCampaignId(campaignId);
			
			if(adgroups == null || adgroups.size() == 0){//该推广计划下没有推广组
				logger.warn("can not find any adgroups, nick is {}, campaign_id is {}", nick, campaignId);
				dto.setMessage("can not find any adgroups");
				requestPool.remove(requestParam);
				return dto;
			}
			
			adgroupIds = new ArrayList<Long>();
			for(Adgroups ad : adgroups){
				adgroupIds.add(ad.getAdgroupId());
			}
		}
		
		String subwayToken = auth.getSubwayTokenByUserId(userId);
		
		if(subwayToken == null){
			logger.warn("can not find subwaytoken, nick is {}, campaign_id is {}", nick, campaignId);
			dto.setMessage("can not find subwaytoken");
			requestPool.remove(requestParam);
			return dto;
		}
		
		String source = "1,2,4,5";
		String searchType = "SEARCH,CAT,NOSEARCH";
		int pageSize = 5000;
		
		List<RptAdgroup> listRes = new ArrayList<RptAdgroup>();
		Map<String, List<Long>> dateRange = new HashMap<String, List<Long>>();
		
		for(Long adgroupId : adgroupIds){
			
			Map<String, String> map = parseDateRange(userId, campaignId, adgroupId, startDate, endDate, dateRange);
		
			logger.info(">>> startTime {}, endTime {}, pageSize {}", map.get("startTime"), map.get("endTime"), map.get("pageSize"));
			
			if(map.get("startTime").compareTo(map.get("endTime")) < 1){
			
				String response = null;
				pageSize = NumberUtils.toInt(map.get("pageSize"), 5000);			
				int pageNo = 1;
				List<RptAdgroup> listTotal = new ArrayList<RptAdgroup>();
				List<RptAdgroup> subList = null;
				try{
					
					do{
						response = proxy.getRptAdgroupBase(subwayToken, nick, campaignId, adgroupId, source, searchType, map.get("startTime"), map.get("endTime"), pageSize, pageNo);
						if(response != null && response.contains("isv.invalid-permission")){//没有权限
							dto.setMessage("invalid-permission");
							requestPool.remove(requestParam);
							return dto;
						}else if(response != null && response.contains("invalid-sessionkey")){
							dto.setMessage("invalid-sessionkey");
							logger.warn("can not get any info from proxy, maybe something is wrong, nick is {}, response {}", nick, response);
							requestPool.remove(requestParam);
							return dto;
						}else if(response == null){
							break;
						}
						
						subList = service.parseJsonToRptAdgroupsBase(response);
						
						if(subList != null && subList.size() > 0){
							listTotal.addAll(subList);
						}
						pageNo++;
					}while(subList != null && subList.size() == pageSize && pageSize > 0);
					
					int restSize = 0; 
				//	int totalEffect = 0;
					pageNo = 1;
					
					if(listTotal != null && listTotal.size() > 0 && pageSize > 0){
						int lastDayRecordTotal = 0;
						int lastDayNoDataNum = 0;
						do{
							response = proxy.getRptAdgroupEffect(subwayToken, nick, campaignId, adgroupId, source, searchType, map.get("startTime"), map.get("endTime"), pageSize, pageNo);						
							Map<String, Integer> lastDayRecord = new HashMap<String, Integer>();
							restSize = service.combineRptAdgroupsEffect(response, lastDayRecord, listTotal);
							lastDayRecordTotal += lastDayRecord.get("total");
							lastDayNoDataNum += lastDayRecord.get("lost");
							//totalEffect+=restSize;
							pageNo++;
						}while(restSize == pageSize);
						
						if(record != null && record.equalsIgnoreCase("yes") 
								&& lastDayRecordTotal > 0 && lastDayNoDataNum == lastDayRecordTotal){//有基础数据，没有效果数据
							
							Date lastDate = Util.getLastDayYYYYMMDD();
							long lastCustRpt = user.countRptCustomerByUserIdDate(userId, lastDate);
							if(lastCustRpt == 0){
								logger.warn("syncRptAdgroups, base data num {}, effect data num is zero, adgroupId is {}", listTotal.size(), adgroupId);
								syncService.updateSyncRecordByProcess("syncRptAdgroup", 1);
								
								continue;
							}							
						}
					}

				}catch(Exception e){
					requestPool.remove(requestParam);
					throw e;
				}
				
				listRes.addAll(listTotal);
			}	
		}
		
		service.updateRptAdgroupsData(userId, listRes);
		
		if(startDate !=null && endDate != null){
			deleteRptDataByDateRange(dateRange);
		}
		
		dto.setAddNum(service.insertRptAdgroupsBatch(listRes));
		
		Date endProcessTime = new Date();
		long durTime = endProcessTime.getTime() - beginProcessTime.getTime();
		dto.setDurTime(durTime);
		
		requestPool.remove(requestParam);
		
		return dto;
	}
	
	
	/************辅助函数******************/
	
	private Map<String, String> parseDateRange(Long userId, Long campaignId,Long adgroupId, String startDate, String endDate, Map<String, List<Long>> dateRange){
		
		Integer pageSize = 5000;
	
		Map<String, String> map = null;
		if(startDate == null || endDate == null){
			Date dateOld = service.getLastTimeFromRpt(userId, campaignId, adgroupId); 
			map = Util.getDateRange(dateOld);
			startDate = map.get("startTime");
			endDate = map.get("endTime");
			pageSize = NumberUtils.toInt(map.get("pageSize"), 5000);
		}
	
		if(startDate.compareTo(endDate) < 1){
			StringBuilder sb = new StringBuilder();
			sb.append(startDate);
			sb.append(",");
			sb.append(endDate);
			String range = sb.toString();
			if(dateRange.containsKey(range)){
				dateRange.get(range).add(adgroupId);
			}else{
				List<Long> idsList = new ArrayList<Long>();
				idsList.add(adgroupId);
				dateRange.put(range, idsList);
			}
		}
		
		if(map == null){
			map = new HashMap<String, String>();
			map.put("startTime", startDate);
			map.put("endTime", endDate);
			map.put("pageSize", pageSize.toString());
		}
		
		return map;
	}
	
	private void deleteRptDataByDateRange(Map<String, List<Long>> dateRange){
		
		for (Map.Entry<String, List<Long>> entry : dateRange.entrySet()){
			
			String key = entry.getKey();
			String[] range = key.split(",");
			Date startDate = new Date();
			Date endDate = startDate;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				startDate = sdf.parse(range[0]);
				endDate = sdf.parse(range[1]);
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		
			List<Long> adgroupIds = entry.getValue();
			service.deleteRptAdgroupsByDateRange(adgroupIds, startDate, endDate);
		}
	}
	
	
}